package com.yiren.dbaa.net.rtk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.communication.api.I4GCommunication;
import com.yiren.backstage.communication.api.impl.Public4GCommunicationApiImpl;
import com.yiren.backstage.communication.thread.RTKConnection;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.SignalSourceConfigBean;
import com.yiren.backstage.config.bean.device.StationParamConfigBean;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.config.enums.RoverStationEnum;
import com.yiren.backstage.currency.constant.Messages4G;
import com.yiren.backstage.currency.utils.GpsUtil;
import com.yiren.backstage.currency.utils.MD5;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.currency.model.ScreenModel;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.net.OkHttpUtils;
import com.yiren.dbaa.net.bean.BaseResponseBean;
import com.yiren.dbaa.net.bean.BaseStationInfoBean;
import com.yiren.dbaa.net.bean.FourGInfoBean;
import com.yiren.dbaa.net.interf.StringCallback;
import com.yiren.dbaa.util.Check4GSignalUtil;
import com.yiren.dbaa.util.GraphicUtil;
import com.yiren.dbaa.util.JinzhiUtil;
import com.yiren.dbaa.util.NetWorkUtil;
import com.yiren.dbaa.view.dialog.CustomDialog;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Create by LJY
 * @Date 2021/5/7 14:59
 * @Desc 绑定基站流程
 */
public class BaseStationHelper implements RTKConnection.OnConnectionListener {

    private Activity activity;
    private UserParamConfigBean userParamConfig;
    private SignalSourceConfigBean signalSourceConfig;
    private StationParamConfigBean stationParamConfig;
    private I4GCommunication i4GCommunication;

    public BaseStationHelper(Activity activity) {
        this.activity = activity;
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
        signalSourceConfig = LoadConfigApi.loadSignalSourceConfig(activity);
        stationParamConfig = LoadConfigApi.loadStationParamConfig(activity);
        i4GCommunication = new Public4GCommunicationApiImpl(activity);
    }

    /**
     * 查看4G信息是否全部获取到了
     */
    public void get4GInfoData(boolean isFirst) {
        if (userParamConfig.isHasGjdInterface() || userParamConfig.isPartner()) {
            if (Check4GSignalUtil.has4GSignal()) {
                if (signalSourceConfig.getRoverStationType().equals(RoverStationEnum.HAS_CARD_ROVER_STATION)) {
                    //有4G
                    have4GMode(isFirst);
                } else {
                    //无4G
                    nothing4GMode(isFirst);
                }
            } else {
                //不能接收4g信号,等待obd升级成功,在去执行读取移动站信息操作
                MessageBox.show(activity, "当前硬件版本号过低，请升级硬件版本！");
            }
        }
    }

    @Override
    public void onDifferenceStateChange(int state, String message) {
//        mActivity.runOnUiThread(() -> MessageBox.show(mActivity, message));
    }

    /**
     * 已选择4G模块流程
     *
     * @param isFirst
     */
    private void have4GMode(boolean isFirst) {
        if (isFirst) {
            if (StringUtils.isEmpty(stationParamConfig.getRoverRegdt())) {
                read4gByModel();
            } else {
                bindBaseStation(stationParamConfig.getRoverRegdt());
            }
        } else {
            RTKConnection.getInstance().stop();
            read4gByModel();
        }
    }

    /**
     * 已选择无4G模块流程
     *
     * @param isFirst
     */
    private void nothing4GMode(boolean isFirst) {
        if (isFirst) {
            if (StringUtils.isEmpty(stationParamConfig.getRoverRegdt())) {
                read4gByInterface();
            } else {
                bindBaseStation(stationParamConfig.getRoverRegdt());
            }
        } else {
            read4gByInterface();
        }
    }

    private boolean isReadable = false;

    private void read4gByModel() {
        isReadable = true;
        //先清空缓存配置
        stationParamConfig.setRoverIccid("");
        stationParamConfig.setRoverVersion("");
        stationParamConfig.setRoverRegdt("");
        ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);

        List<String> messages = new ArrayList<>();
        messages.add(Messages4G.FOURG6);
        messages.add(Messages4G.FOURG13);
        messages.add(Messages4G.FOURG5);
        LoadDialog.show(activity, "移动基站信息读取中");
        LoadDialog.setOnDismissListener((LoadDialog.OnDismissListener) dialog -> {
            if (isReadable) {
                LoadDialog.show(activity, "移动基站信息读取中");
            }
        });
        i4GCommunication.get4GInfo(messages, new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.arg1) {
                    case 1:
                        String data = (String) msg.obj;
                        if (StringUtils.isNotEmpty(data)) {
                            String[] split = data.split(":");
                            if (split.length <= 1) {
                                break;
                            }
                            String datas = split[1].trim();
                            if (data.contains("ICCID")) {
                                stationParamConfig.setRoverIccid(datas);
                            } else if (data.contains("VER")) {
                                stationParamConfig.setRoverVersion(datas);
                                isReadable = false;
                            } else if (data.contains("REGDT")) {
                                String netId = JinzhiUtil.hexStringToString(datas);
                                stationParamConfig.setRoverRegdt(netId);
                            }
                            ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);
                        }
                        break;
                    case 2: //结束4G模块如果还没有获取到数据，则重新获取数据
                        isReadable = false;
                        String iccidData = stationParamConfig.getRoverIccid();
                        ;
                        //网络识别号
                        String netRecogData = stationParamConfig.getRoverRegdt();
                        if ((iccidData.equals("") || netRecogData.equals(""))) {
                            if (!isShowing) {
                                read4GInfoFailure();
                            }
                        } else {  //读取成功,则去绑定固定站
                            bindBaseStation(netRecogData);
                        }
                        LoadDialog.dismiss(activity);
                        break;
                    case 3:  //如果OBD不接受4G信号，则过3秒返回消息
                        isReadable = false;
                        if (!isShowing) {
                            read4GInfoFailure();
                        }
                        LoadDialog.dismiss(activity);
                        break;
                    default:
                        LoadDialog.dismiss(activity);
                        isReadable = false;
                        break;
                }
            }
        });
    }

    private boolean isShowing = false;
    private int readCount = 0;

    /**
     * 读取4G信息失败
     */
    private void read4GInfoFailure() {
        if (readCount > 0) {  //提示失败弹框 该弹框需要出ui
            showOBDFailDialog();
            readCount = 0;
            return;
        }
        isShowing = true;
        if (!activity.isFinishing()) {
            final AlertDialog dialog = new AlertDialog.Builder(activity).create();
            dialog.show();
            dialog.setCancelable(false);
            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
            ScreenModel screen = GraphicUtil.getResolutionInfo(activity);
            params.width = (screen.getWidth() * 4) / 10;
            params.height = (screen.getHeight() * 5) / 10;
            dialog.getWindow().setAttributes(params);
            Window window = dialog.getWindow();
            window.setContentView(R.layout.dialog_base_station_status);
            ImageView ivBaseStation = (ImageView) window.findViewById(R.id.iv_base_station);
            TextView tvStatusInfo = (TextView) window.findViewById(R.id.tv_status_info);
            LinearLayout llMyKnow = (LinearLayout) window.findViewById(R.id.ll_my_know);
            TextView tvBaseAction = (TextView) window.findViewById(R.id.tv_base_action);
            ivBaseStation.setVisibility(View.VISIBLE);
            ivBaseStation.setImageResource(R.mipmap.gjd_status3);
            tvStatusInfo.setText("信息读取失败，请进行重新读取");
            tvBaseAction.setText("重新读取");
            llMyKnow.setVisibility(View.VISIBLE);
            llMyKnow.setOnClickListener(v -> {
                isShowing = false;
                readCount++;
                dialog.dismiss();
                get4GInfoData(false);
            });
        }
    }

    /**
     * 显示obd多次连接失败的弹框
     */
    private void showOBDFailDialog() {
        if (!activity.isFinishing()) {
            AlertDialog dialog = new AlertDialog.Builder(activity).create();
            dialog.show();
            dialog.setCancelable(false);
            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
            ScreenModel screen = GraphicUtil.getResolutionInfo(activity);
            params.width = (screen.getWidth() * 4) / 10;
            params.height = (screen.getHeight() * 5) / 10;
            dialog.getWindow().setAttributes(params);
            Window window = dialog.getWindow();
            window.setContentView(R.layout.dialog_base_station_status);
            ImageView ivBaseStation = (ImageView) window.findViewById(R.id.iv_base_station);
            TextView tvStatusInfo = (TextView) window.findViewById(R.id.tv_status_info);
            LinearLayout llMyKnow = (LinearLayout) window.findViewById(R.id.ll_my_know);
            TextView tvBaseAction = (TextView) window.findViewById(R.id.tv_base_action);
            ivBaseStation.setVisibility(View.VISIBLE);
            ivBaseStation.setImageResource(R.mipmap.gjd_status3);
            tvStatusInfo.setText("请检查OBD主机盒线路是否正常,如正常,请重启OBD主机盒.如还不能解决请联系运维人员");
            tvBaseAction.setText("确定");
            llMyKnow.setVisibility(View.VISIBLE);
            llMyKnow.setOnClickListener(v -> {
                dialog.dismiss();
            });
        }
    }

    /**
     * 绑定基站
     */
    private void bindBaseStation(String regdt) {
        String base_station_id = stationParamConfig.getBaseStationId();
        if (StringUtils.isEmpty(base_station_id)) {
            MessageBox.show(activity, "当前考场没有绑定固定站！");
        } else if (userParamConfig.getSite() == null) {
            //提示去下载考场数据
            whileNoSiteData();
        } else {
            //当前移动站id跟之前的不一致,需要换绑
            if (!NetWorkUtil.isNetworkAvailable(activity)) {
                MessageBox.show(activity, "您的网络处于断开的状态,请检查网络");
            } else {
                switchData(base_station_id, regdt);
            }
        }
    }

    /**
     * 通过接口获取4g模块
     */
    private void read4gByInterface() {
        if (NetWorkUtil.isNetworkConnected(activity)) {
            OkHttpUtils.getInstance().postJsonString(activity, AddressConstant.get4gInfoByInterface(), "", new StringCallback() {
                @Override
                public void getString(String result) {
                    BaseResponseBean<FourGInfoBean> responseBean = new Gson().fromJson(result, new TypeToken<BaseResponseBean<FourGInfoBean>>() {
                    }.getType());
                    if (responseBean.getError() == null) {
                        stationParamConfig.setRoverIccid(responseBean.getResult().getFOUR_G_ICCID());
                        stationParamConfig.setRoverVersion(responseBean.getResult().getFOUR_G_VER());
                        stationParamConfig.setRoverRegdt(responseBean.getResult().getFOUR_G_REGDT());
                        ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);
                        bindBaseStation(responseBean.getResult().getFOUR_G_REGDT());
                    } else {
                        MessageBox.show(activity, responseBean.getError().getMessage());
                    }
                }
            });
        } else {
            MessageBox.show(activity, "当前网络连接不可用，请检查您的网络！");
        }
    }

    /**
     * 先下载考场数据再进行线路管理
     */
    private void whileNoSiteData() {
        if (activity.isFinishing()) return;
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        builder.setMessage("暂无考场数据\n请先下载考场数据再进行线路管理\n是否立即下载考场数据？");
        builder.setTitle("温馨提示");
        builder.setCanceled(false);
        builder.setPositiveButton("下载", (dialog, which) -> {
            Intent intent = activity.getIntent();
            intent.setClass(activity, PracticeCarSetActivity.class);
            intent.putExtra("isUnData", true);
            activity.startActivity(intent);
            dialog.dismiss();
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        if (!activity.isFinishing()) {
            builder.create().show();
        }
    }

    /**
     * 发送移动站换绑固定基站请求
     */
    private void switchData(final String deviceBase, final String deviceRover) {
        String KEY = "com.yr.dj.yikj";
        String sign = MD5.md5(deviceBase + deviceRover + KEY);
        Map<String, Object> map = new HashMap<>();
        map.put("sign", sign);
        map.put("deviceBase", deviceBase);
        map.put("deviceRover", deviceRover);
        OkHttpUtils.getInstance().postJsonString(activity, AddressConstant.bindDeviceBase(), new Gson().toJson(map), new StringCallback() {
            @Override
            public void getString(String result) {
                LoadDialog.dismiss(activity);
                if (StringUtils.isNotEmpty(result) && "SUCCESS".equals(result)) {
                    //移动站换绑成功
                    stationParamConfig.setBaseStationId(deviceBase);
                    ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);
                    if (signalSourceConfig.getRoverStationType().equals(RoverStationEnum.NO_CARD_ROVER_STATION)) {
                        RTKConnection rtkConnection = RTKConnection.getInstance();
                        rtkConnection.setOnConnectionListener((state, message) -> activity.runOnUiThread(() -> MessageBox.show(activity, message)));
                        rtkConnection.setDiffId(deviceRover);
                        rtkConnection.start();
                    }
                    getStationInfo(deviceBase);
                } else {
                    CommonDialog.showOneBtn(activity, "温馨提示", "基站绑定失败\r\n，会影响您的正常使用，请手动切换或重启APP", "我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取基站标定状态和经纬高
     *
     * @param deviceBase 基站id
     */
    private void getStationInfo(String deviceBase) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.getStationLocation("?deviceBase=" + deviceBase), new StringCallback() {
            @Override
            public void getString(String result) {
                if (StringUtils.isNotEmpty(result)) {
                    BaseStationInfoBean model = new Gson().fromJson(result, BaseStationInfoBean.class);
                    if (StringUtils.isNotEmpty(model.getIsUpdate().toString())) {
                        float isUpdate = Float.parseFloat(model.getIsUpdate().toString());
                        stationParamConfig.setBaseCalibration(isUpdate == 1);
                        if (isUpdate == 1) {  //基站已标定，将基站坐标转换为百度坐标系使用
                            stationParamConfig.setBaseStationLocation(GpsUtil.getBdCoornates(Double.parseDouble(model.getLat().toString()), Double.parseDouble(model.getLng().toString()), Double.parseDouble(model.getHigh().toString())));
                        } else {
                            stationParamConfig.setBaseStationLocation("");
                        }
                        ParamConfigApi.saveStationParamConfig(activity, stationParamConfig);
                    }
                }
            }
        });
    }

}
